package com.xtourms.server;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.xtourms.client.rm.product.ProductService;
import com.xtourms.server.db.City;
import com.xtourms.server.db.Product;
import com.xtourms.server.db.Worker;
import com.xtourms.server.db.core.DBOper;
import com.xtourms.shared.field.HotelField;
import com.xtourms.shared.field.ProductField;

@SuppressWarnings("serial")
public class ProductServiceImpl extends RemoteServiceServlet implements ProductService{

	@Override
	public String cOrMProduct(String productInfo) {
		String ret = null;
		Session session = DBOper.openSession();
		Transaction t = session.beginTransaction();
		try {
			t.begin();
			
			Product hotel = null;
			JSONObject pdtObj = new JSONObject(productInfo);
			int hId = pdtObj.optInt(ProductField.PDT_ID);
			if (0 != hId) {
				hotel = (Product)session.load(Product.class, Integer.valueOf(hId));
			}else{
				hotel = new Product();
			}
			
			fillProduct(hotel, pdtObj);
			
			session.save(hotel);
			t.commit();
			ret = toJSONProduct(hotel, session).toString();
			session.close();
		} catch (JSONException e) {
			t.rollback();
		}
		return ret;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String queryProduct(String condition) {
		String hql = "from Product pdt";
		try {
			JSONObject condObj = new JSONObject(condition);
			int cityId = condObj.optInt(ProductField.PDT_CITY_ID);
			hql += " where pdt.productCity=" + cityId;
			String pdtName = condObj.optString(ProductField.PDT_NAME);
			if (!pdtName.isEmpty()) {
				hql += " and pdt.productName like '%" + pdtName + "%'";
			}
			int lPrice = condObj.optInt(ProductField.LOW_PRICE);
			int hPrice = condObj.optInt(ProductField.HIGH_PRICE);
			if(hPrice !=0){
				hql += " and pdt.productSellPrice between "+ lPrice +" and "+hPrice; 
			}else{
				hql += " and pdt.productSellPrice>="+ lPrice;
			}
			String inDate = condObj.optString(HotelField.IN_DATE);
			if(inDate.isEmpty()){
				hql += " and '"+ inDate +"' between pdt.productStartDate and pdt.productEndDate";
			}
		} catch (JSONException e1) {
			e1.printStackTrace();
		}

		Session s = DBOper.openSession();
		Transaction t = s.beginTransaction();
		try{
			t.begin();
			Query query = s.createQuery(hql);
			//TODO:分页
			query.setFirstResult(0);
			query.setMaxResults(20);
			List<Product> pdtList = query.list();
			
			Iterator<Product> pdtIter = pdtList.iterator();
			JSONArray ret = new JSONArray();
			while (pdtIter.hasNext()) {
				Product pdt = pdtIter.next();
				try {
					JSONObject pdtObj = toJSONProduct(pdt, s);
					ret.put(pdtObj);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			s.close();
			return ret.toString();
		}catch (Exception e) {
			t.rollback();
		}
		return null;
	}

	private JSONObject toJSONProduct(Product pdt, Session s) throws JSONException{
		JSONObject ret = new JSONObject();
		ret.put(ProductField.PDT_ID, pdt.getProductId());
		ret.put(ProductField.PDT_NAME, pdt.getProductName());
		ret.put(ProductField.PDT_CITY_ID, pdt.getProductCity());
		int cid = pdt.getProductCity();
		City city = (City) s.load(City.class, Integer.valueOf(cid));
		ret.put(ProductField.PDT_CITY_NAME, city.getCityName());
		ret.put(ProductField.PDT_PROVINCE_ID, city.getProvince()
				.getProvinceId());
		ret.put(ProductField.PDT_PROVINCE_NAME, city.getProvince()
				.getProvinceName());
		ret.put(ProductField.PDT_DES, pdt.getProductDes());
		ret.put(ProductField.PDT_BP, pdt.getProductBasePrice());
		ret.put(ProductField.PDT_SP, pdt.getProductSellPrice());
		ret.put(ProductField.PDT_SD, pdt.getProductStartDate()
				.toString());
		ret.put(ProductField.PDT_ED, pdt.getProductEndDate().toString());
		int workerId = pdt.getLastmodifyWorker();
		
		ret.put(ProductField.PDT_MANAGER_NAME, pdt.getProductManagerName());
		ret.put(ProductField.PDT_MANAGER_PHONE, pdt.getProductManagerPhone());
		ret.put(ProductField.PDT_LINKMAN_NAME, pdt.getProductLinkmanName());
		ret.put(ProductField.PDT_LINKMAN_PHONE, pdt.getProductLinkmanPhone());
		ret.put(ProductField.PDT_LINKMAN_QQ, pdt.getProductLinkmanQq());
		
		Worker worker = (Worker) s.load(Worker.class, Integer
				.valueOf(workerId));
		
		ret.put(ProductField.LASTMODIFY_WORKER_NAME, worker.getWorkerName());
		ret.put(ProductField.LASTMODIFY_TIME, pdt.getLastmodifyTime());

		return ret;
	}

	private void fillProduct(Product pdt, JSONObject pdtObj) throws JSONException {
		String pdtName = pdtObj.getString(ProductField.PDT_NAME);
		pdt.setProductName(pdtName);
		int pdtCity = pdtObj.getInt(ProductField.PDT_CITY_ID);
		pdt.setProductCity(pdtCity);
		String pdtDes = pdtObj.optString(ProductField.PDT_DES);
		pdt.setProductDes(pdtDes);
		int bp = pdtObj.getInt(ProductField.PDT_BP);
		pdt.setProductBasePrice(bp);
		int sp = pdtObj.getInt(ProductField.PDT_SP);
		pdt.setProductSellPrice(sp);
		String beginDate = pdtObj.getString(ProductField.PDT_SD);
		Date pdtBeginDate = java.sql.Date.valueOf(beginDate);
		pdt.setProductStartDate(pdtBeginDate);
		String endDate = pdtObj.getString(ProductField.PDT_ED);
		Date pdtEndDate = java.sql.Date.valueOf(endDate);
		pdt.setProductEndDate(pdtEndDate);
		
		String pdtManagerName = pdtObj
				.optString(ProductField.PDT_MANAGER_NAME);
		pdt.setProductManagerName(pdtManagerName);
		String pdtManagerTel = pdtObj
				.optString(ProductField.PDT_MANAGER_PHONE);
		pdt.setProductManagerPhone(pdtManagerTel);
		String pdtLinkmanName = pdtObj
				.optString(ProductField.PDT_LINKMAN_NAME);
		pdt.setProductLinkmanName(pdtLinkmanName);
		String pdtLinkmanQq = pdtObj
				.optString(ProductField.PDT_LINKMAN_QQ);
		pdt.setProductLinkmanQq(pdtLinkmanQq);
		String pdtLinkmanTel = pdtObj
				.optString(ProductField.PDT_LINKMAN_PHONE);
		pdt.setProductLinkmanPhone(pdtLinkmanTel);


		

		int lastmodifyWorker = pdtObj
				.getInt(ProductField.LASTMODIFY_WORKER);
		pdt.setLastmodifyWorker(lastmodifyWorker);		
	}
}
